/**
 * 菜单管理
 * @author taojiang
 * @since 2013-10-24
 */
//选择icon
function setIcon(id){
	Ext.ComponentMgr.all.map.icon.setValue(Ext.getCmp('icon').setValue(id));
	//alert(id);
	//alert(Ext.util.Format.substr(id,9,100));
	Ext.getCmp('icon').setValue(Ext.util.Format.substr(id,20,100));
	var tImp = document.createElement('img');
	tImp.src = basePath+id;
	tImp.width='16';
	tImp.height='16';
	tImp.style.cssText="cursor:pointer";
	
	if(Ext.ComponentMgr.all.map.icon.el.dom.parentNode.childNodes.length>1){
		Ext.ComponentMgr.all.map.icon.el.dom.parentNode.removeChild
		(Ext.ComponentMgr.all.map.icon.el.dom.parentNode.childNodes[1]);
	}
	Ext.ComponentMgr.all.map.icon.el.dom.parentNode.appendChild(tImp);
} 
function setMainIcon(id){
	Ext.getCmp('icon').setValue(id);
}

Ext.onReady(function() {
		
	Ext.QuickTips.init();
		
	 	var imgstore = new Ext.data.ArrayStore({
	        proxy   : new Ext.data.MemoryProxy(),
	        fields  : ['id', 'name'],
	        sortInfo: {
	            field    : 'name',
	            direction: 'ASC'
	        }
	    });
	 	imgstore.loadData ([
		                             
		                             ['/images/house.png', '图标1'],
		                             ['/images/bricks.png', '图标2'],
			                         ['/images/rgb.png', '图标3'],
				                     ['/images/chart_bar.png', '图标4'],
				                     ['/images/computer.png', '图标5']
				                    

		                         ]);
	 	Ext.namespace('Ext.exampledata');
	 	Ext.exampledata.states = [   
		                             ['/images/house.png', '图标1'],
		                             ['/images/bricks.png', '图标2'],
			                         ['/images/rgb.png', '图标3'],
				                     ['/images/chart_bar.png', '图标4'],
				                     ['/images/computer.png', '图标5']
	 	                          ];
		  var iconStore = new Ext.data.ArrayStore({
		        fields: ['myId', 'displayText'],
		        data : Ext.exampledata.states // from states.js
		    });
	 	
	 	
	//左边菜单树 新增/修改/删除	
	var tbar = new Ext.Toolbar({
		items : [ {
			text : '新增',
			handler:function(){
	        addtitle.getForm().reset();
			var newwindow_1 = new Ext.Window({
						layout : 'fit',
						width : 700,
						height : 400,
						closable : false,
						resizable : false,
						closeAction : 'hide',
						closable : true,
						constrain : true,
						modal : true,
						autoScroll : true,
						animCollapse : false,
						border : false,
						animateTarget : Ext.getBody(),
						constrain : true,
						buttonAlign:'center',
						items : [ {
							layout : 'column',
							border : false,
							items : [ {
								columnWidth : .65,
								layout : 'form',
								border : false,
								items : [ addtitleWin]
							},{
								columnWidth : .35,
								layout : 'form',
								border : false,
								items : [ accordion ]
							} ]
						} ],
						buttons:[{
									text:'保存 ',
									handler:function(){
									fwInfoStore.load();
									var t = Ext.getCmp("parentIds").getValue();
									debugger;		      
									var m =  Ext.getCmp("modFuncIds").getValue();

									Ext.Ajax.request({
										url : basepath + '/CntMenu-action.json',
										method : 'POST',
										params : {
										'parentId' : Ext.getCmp("parentIds").getValue(),
										'name' : Ext.getCmp("names").getValue(),
										'modFuncId' : Ext.getCmp("modFuncIds").getValue(),
										'issamewin' : Ext.getCmp("issamewins").getValue(),
										'order_' : Ext.getCmp("orders").getValue(),
										'icon' : Ext.getCmp("icons").getValue()
									},
									waitMsg : '正在保存数据,请等待...', // 显示读盘的动画效果，执行完成后效果消失
									scope : this,
									success : function() {
										 Ext.Ajax.request({
								         url: basepath +'/CntMenu-action!getPid.json',
									         success:function(response){
									        	 var node = {};
									        	 node.id = Ext.util.JSON.decode(response.responseText).pid;
									        	 node.name = Ext.getCmp("name").getValue();
									        	 node.parentId = Ext.getCmp("parentId").getValue();
									        	 leftTreeForShow.addNode(node);
										 	}
										 });
										 Ext.Msg.alert('提示', '操作成功');
									},
									failure : function() {
										Ext.Msg.alert('提示', '操作失败');
									}
							        }
								  );
								  newwindow_1.hide();
								}
							},{
      				  			text: '关闭',
       				  			handler:function(){
        			 		    newwindow_1.hide();
        						}
   			 				}]
					});
					newwindow_1.show();
				   /* var formPanelDropTargetEl =  addtitleWin.getForm().findField('funcNames').getEl().dom;

					var formPanelDropTarget = new Ext.dd.DropTarget(formPanelDropTargetEl, {
						ddGroup     : 'gridDDGroup',
						notifyEnter : function(ddSource, e, data) {
						addtitleWin.body.stopFx();
						addtitleWin.body.highlight();
						},
						notifyDrop  : function(ddSource, e, data){
						var selectedRecord = ddSource.dragData.selections[0];
						debugger;
						 Ext.getCmp('modFuncIds').setValue((selectedRecord.data.id));
						 Ext.getCmp('funcNames').setValue((selectedRecord.data.funcName));
		    	   		 Ext.getCmp('parentNames').focus();

							return(true);
						}
					});*/
					/*var formPanelDropTargetE2 = addtitleWin.getForm().findField('parentNames').getEl().dom;
				    

					var formPanelDropTarget = new Ext.dd.DropTarget(formPanelDropTargetE2, {
						ddGroup : 'gridDDGroups',
						notifyEnter : function(ddSource, e, data) {
						addtitleWin.body.stopFx();
						addtitleWin.body.highlight();
						},
						notifyDrop  : function(ddSource, e, data){
							var selectedRecord = ddSource.dragData.node;
							debugger;
							 Ext.getCmp('parentIds').setValue((selectedRecord.attributes.id));
							 Ext.getCmp('parentNames').setValue((selectedRecord.attributes.NAME));
			    	   		 Ext.getCmp('icons').focus();

							return(true);
						}
					});*/

					

					}
		},'-', {
			text : '修改',
			handler : function() {
				var record = leftTreeForShow.getSelectionModel().getSelectedNode();
				debugger;
				if (Ext.isEmpty(record)) {
					Ext.MessageBox.alert('提示', '请先选择要修改菜单项!');
				}else if(record.id == 'root')
				{
					Ext.MessageBox.alert('提示', '根节点不能修改 !');

				}else{
					Ext.getCmp("ids").setValue(record.attributes.id);
					Ext.getCmp("names").setValue(record.attributes.NAME);
					Ext.getCmp("modFuncIds").setValue(record.attributes.MOD_FUNC_ID);
					Ext.getCmp("funcNames").setValue(record.attributes.FUNC_NAME);
					Ext.getCmp("parentIds").setValue(record.attributes.PARENT_ID);
					Ext.getCmp("parentNames").setValue(record.attributes.PARENT_NAME);
					Ext.getCmp("orders").setValue(record.attributes.ORDER_);
					 
					 var i = asStore.find('myId',record.attributes.ISSAMEWIN);//反显出汉字，不是码值
						if(i!=-1){
							Ext.getCmp('issamewins').setValue(asStore.getAt(i).get('displayText'));
						}
						else
						{
							Ext.getCmp('issamewins').setValue((asStore.attributes.ISSAMEWIN));
						}
						 
						 if(record.attributes.icon != undefined ){
								Ext.getCmp('icons').setValue((record.attributes.ICON));
						 }
               	var store = Ext.data.Store;
					var newwindow_1 = new Ext.Window({
						layout : 'fit',
						width : 800,
						height : 500,
						closable : true,
						draggable : true,
						title : '修改菜单',
						closeAction : 'hide',
						titleCollapse : true,
						modal : true, // 模态窗口 
						animCollapse : false,
						border : false,
						animateTarget : Ext.getBody(),
						constrain : true,
						buttonAlign:'center',
						items : [ {
							layout : 'column',
							border : false,
							items : [ {
								columnWidth : .65,
								layout : 'form',
								border : false,
								items : [addtitleWin]
							}, {
								columnWidth : .35,
								layout : 'form',
								border : false,
								items : [ accordion ]
							} ]
						} ],
						buttons:[{
							text:'保存',
							handler:function(){
							debugger;
							if(Ext.getCmp("parentId").getValue()==Ext.getCmp('id').getValue()){
								Ext.Msg.alert('提示', '当前菜单不能做为上层菜单!否则会出现未知错误');
								return false;
							    }else{
									if(!addtitleWin.getForm().isValid()){ 
									 Ext.MessageBox.alert('提示','输入有误,请检查输入项');
									 return false;
									}
									Ext.Ajax.request({
									url : basepath + '/CntMenu-action!update_new.json',
									method : 'POST',
									params : {
									'name' : Ext.getCmp("names").getValue(),
									'parentId':Ext.getCmp("parentIds").getValue(),
									'id' :Ext.getCmp('ids').getValue(),
									'icon':Ext.getCmp('icons').getValue(),
									'order':Ext.getCmp('orders').getValue(),
									'modFuncId':Ext.getCmp('modFuncIds').getValue(),
									'issamewin':Ext.getCmp('issamewins').getValue()

									},
									waitMsg : '正在保存数据,请等待...', // 显示读盘的动画效果，执行完成后效果消失
									//修改文档的目录
									scope : this,
									success : function() {
					
											 Ext.Msg.alert('提示', '操作成功');
											 custGroupStore.load();
											 var node = {};
											 node.id = Ext.getCmp("ids").getValue();
								        	 node.text = Ext.getCmp("names").getValue();
								        	 node.parentId = Ext.getCmp("parentIds").getValue();
								        	 node.icon = Ext.getCmp('icons').getValue(),
                                             node.modFuncId = Ext.getCmp('modFuncIds').getValue(),
                                             node.order = Ext.getCmp('orders').getValue(),
                                             node.issamewin = Ext.getCmp('issamewins').getValue(),
								        	 leftTreeForShow.editNode(node);
									    },  
										    failure : function() {
											Ext.Msg.alert('提示', '操作失败');
									        }
									
							        }
								  );
								
							}


							  newwindow_1.hide();
							  /*  var formPanelDropTargetE3 =  addtitleWin.getForm().findField('funcNames').getEl().dom;
								var formPanelDropTarget = new Ext.dd.DropTarget(formPanelDropTargetE3, {
									ddGroup     : 'gridDDGroup',
									notifyEnter : function(ddSource, e, data) {
									addtitleWin.body.stopFx();
									addtitleWin.body.highlight();
									},
									notifyDrop  : function(ddSource, e, data){

										// Reference the record (single selection) for readability
										var selectedRecord = ddSource.dragData.selections[0];
										debugger;
										 Ext.getCmp('modFuncIds').setValue((selectedRecord.data.id));
									    Ext.getCmp('funcNames').setValue((selectedRecord.data.funcName));

							
										return(true);
									}
								});		*/  
							}
						},{
      				  		text: '取消',
       				  		handler:function(){
        			 		newwindow_1.hide();
        					}
   			 			}]
					});
					newwindow_1.show();}
			}
	    	},'-',{
			text:'删除',
			handler:function(){
			var record = leftTreeForShow.getSelectionModel().getSelectedNode();
			if (Ext.isEmpty(record)) {
				Ext.MessageBox.alert('提示', '请先选择要删除的菜单!');
			}else{
					Ext.Msg.confirm(
							'请确认','确定删除吗?',
							function(btn, text) {
								if (btn == 'yes') {
									Ext.Ajax.request({
										url : basepath + '/CntMenu-action!batchDestroy.json',
										method : 'POST',
										params : {
										'id' : Ext.getCmp("id").getValue()
										},
										waitMsg : '正在保存数据,请等待...', // 显示读盘的动画效果，执行完成后效果消失
										scope : this,
										success : function() {
								        	 leftTreeForShow.deleteNode(record);
								        	 Ext.Msg.alert('提示', '操作成功');
								        	
										},
										    failure : function() {
											Ext.Msg.alert('提示', '操作失败');
										}
								        }
									  );
									}
								});
					}
				}
			}]
	})
	
	var addtitleWin=new Ext.form.FormPanel({
		id:'addtitleWin',
		title : '菜单设置',
	    frame:true,
	    region:'north',
	    bodyStyle:'padding:5px 5px 0',
	    width: '100%',
	  	height:380,
	  	autoScroll : true,
		split:true,
	    items: [{
	    	items :[{  
	            layout:'column',
	            items:[{
                columnWidth:.80,
             	layout: 'form',
             	items: [{
					 id:'idWin',
					 xtype:'textfield',
					 fieldLabel: '当前用户ID',
					 name: 'name',
					 hidden : true,
					 anchor:'95%'
					},{
						 allowBlank: false,
						 id:'nameWin',
						 xtype:'textfield',
					    fieldLabel: '名称<font color=red>*</font>',
					    readOnly:true,
					    name: 'name',
					    anchor:'95%'
					}, {
					    id:'iconWin',
					    xtype:'textfield',
					    fieldLabel: '图标',
					    readOnly:true,
					    name: 'icon',
					    anchor:'95%'
					},{
					    id:'isLeafWin',
					    xtype:'textfield',
					    fieldLabel: '是否叶子菜单',
					    readOnly:true,
					    name: 'isLeaf',
					    anchor:'95%'
					},{
					    id:'urlWin',
					    xtype:'textfield',
					    fieldLabel: 'URL',
					    readOnly:true,
					    name: 'url',
					    anchor:'95%'
					},{
						id:'orderWin',
						name:'order',
						xtype:'textfield',
						readOnly:true,
						fieldLabel: '排序',
						anchor:'95%'
					},{
						id:'parentIdWin',
						name:'parentId',
						xtype:'textfield',
						readOnly:true,
						fieldLabel: '上层菜单选择',
						anchor:'95%',
						hidden : true
					   },{
						   	id:'parentNameWin',
						   	name:'parentName',
						   	xtype:'textfield',
						   	readOnly:true,
						   	allowBlank : false,
						   	fieldLabel: '上层菜单选择',
						    anchor:'95%'
					   }             
								                     	   ]}
				                     	]}
				            	]}
			        	]
		
	})
	//图标加载
	
    var dataView = new Ext.DataView({
        store: imgstore,
        id: 'iconss',
        tpl  : new Ext.XTemplate(
            '<ul>',
                '<tpl for=".">',
                    '<li onclick="setIcon(\'{[values.id]}\')" style="float:left;margin-left:12px;margin-right:12px;margin-top:10px;">',
                    '<img src= "'+basePath+'/{[values.id]}" />',
                    '</li>',
                '</tpl>',
            '</ul>'
        ),
        itemSelector: 'li.icon',
        overClass   : 'phone-hover',
        singleSelect: true,
        autoScroll  : true
       // overClass:'x-view-over',//鼠标悬停item时的类样式,defaults to undefined
        //itemSelector:'div.thumb-wrap'//必须项,值为item选择器,此值也可为.thumb-wrap  e.g. div.some-class

    });
	
	 var iconView = new Ext.Panel({
	        title: '图标',
	        id :'iconView',
			ddGroup  : 'gridDDGroups1',
			enableDD  : true,
	        layout: 'fit',
	        items : [dataView],
	        height: 700,
	        width: 300
	    });
	    var accordion = new Ext.Panel({
	        region:'west',
	        margins:'5 10 5 0',
	        split:true,
	        width: 280,
	        layout:'accordion',
	        items: [iconView]
	    });
	
		var addtitle=new Ext.form.FormPanel({
			id:'addtitle',
			title : '菜单设置',
		    frame:true,
		    region:'north',
		    bodyStyle:'padding:5px 5px 0',
		    width: '100%',
		  	height:380,
		  	autoScroll : true,
			split:true,
		    items: [{
		    	items :[{  
		            layout:'column',
		            items:[{
                    columnWidth:.50,
                 	layout: 'form',
                 	items: [{
						 id:'id',
						 xtype:'textfield',
						fieldLabel: '当前用户ID',
						name: 'name',
						hidden : true,
						anchor:'95%'
						},{
							 allowBlank: false,
							 id:'name',
							 xtype:'textfield',
						    fieldLabel: '名称<font color=red>*</font>',
						    readOnly:true,
						    name: 'name',
						   anchor:'95%'
						}, {
						    id:'icon',
						    xtype:'textfield',
						    fieldLabel: '图标',
						    readOnly:true,
						    name: 'icon',
						    anchor:'95%'
						},{
						    id:'isLeaf',
						    xtype:'textfield',
						    fieldLabel: '是否叶子菜单',
						    readOnly:true,
						    name: 'isLeaf',
						    anchor:'95%'
						},{
						    id:'url',
						    xtype:'textfield',
						    fieldLabel: 'URL',
						    readOnly:true,
						    name: 'url',
						    anchor:'95%'
						},{
							id:'order',
							name:'order',
							xtype:'textfield',
							readOnly:true,
							fieldLabel: '排序',
							anchor:'95%'
						},{
							id:'modFuncId',
							name:'modFuncId',
							xtype:'textfield',
							readOnly:true,
							fieldLabel: '功能模块选择',
							hidden:true,
							anchor:'95%'
						
						},{
							id:'parentId',
							name:'parentId',
							xtype:'textfield',
							readOnly:true,
							fieldLabel: '上层菜单选择',
							anchor:'95%',
							hidden : true
						   },{
							   	id:'parentName',
							   	name:'parentName',
							   	 xtype:'textfield',
							   	 readOnly:true,
							   	 allowBlank : false,
							   	fieldLabel: '上层菜单选择',
							    anchor:'95%'
						   }             
									                     	   ]}
					                     	]}
					            	]}
				        	]
			
		})
		//布局
		new Ext.Viewport({
			layout:'border',
		        items:[{
		 	        region: 'west',
		 	        collapsible: false,
		 	        title: '菜单管理',
		 	        xtype: 'treepanel',
		 	        width: 200,
		 	        tbar:tbar,
		 	        autoScroll: false,
		 	        split: false,
		 	        loader: new Ext.tree.TreeLoader(),
		 	        root: new Ext.tree.AsyncTreeNode({
		 	        	id:'root',
		 	            expanded: true,
		 	            text:'菜单管理',
		 	            children: [{
		 	                text: '总行对分支行评价体系',
		 	                leaf: true
		 	            }, {
		 	                text: '分行评价体系',
		 	                leaf: true
		 	            }]
		 	        }),
		 	        rootVisible: true,
		 	        listeners: {
		 	            click: function(n) {
		 	            	Ext.getCmp('icsysname').setValue(n.attributes.text );
		 	            }
		 	        }
		        },{
		            region:'center',
		            layout:'fit',
		           	items:[{
		           		layout:'border',
		           		split:true,
	            		minSize: 100,
	           			maxSize: 300,
		           		items:[{
		           			id:'center-panel',
		           			region:'center',
		           			layout:'fit',
		           			items:[addtitle]
		           		}]
		           	}]
		        }]
		});	
		Ext.Ajax.request({//左侧菜单项树的Ajax请求事件
			url : basepath + '/menuInit.json',
			method:'GET',
			success:function(response){
				var nodeArra = Ext.util.JSON.decode(response.responseText);
				Ext.each(nodeArra.json.data,function(n){
					if(n.ICON){
						var test;
						test = Ext.util.Format.substr(n.ICON,0,1);
						if(test=='/')
						{n.icon = basepath+'/'+'/skin/default/common'+n.ICON;//对从台读取图标数据进行处理，变成绝对路径，那样才能显示图标
						}else{
							n.icon = '';
						}
					}
				});
				loader.nodeArray = nodeArra.json.data;
				var children = loader.loadAll();
				leftTreeForShow.appendChild(children);
				rightMenuTreeShow.appendChild(children);
			}
		});
		
});